package com.sunni.repository.impl;

import com.sunni.entity.Admin;
import com.sunni.repository.AdminRepository;
import com.sunni.utils.JDBCTool;

import java.sql.*;

public class AdminRepositoryImpl implements AdminRepository {
    private Connection connection=null;
    private PreparedStatement preparedStatement=null;
    private ResultSet resultSet=null;


    @Override
    public Admin login(String username, String password) {
        // ***进了方法，先给返给前台的对象 初始化，，，不然如果 不初始化，每次川汇区都是上次的值（在堆中 不会被清理）。******
        Admin admin=null;  // 初始值必须为null, 每次进这个方法里面都重新赋值null。不然的话上一次的结果还在堆里放着，如果下面没进resultSet的循环，那么就还是引用的上次的结果。
        try {
            connection = JDBCTool.getConnection();
            String sql = "select * from bookadmin where username=? and password=?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,username);
            preparedStatement.setString(2,password);

            resultSet = preparedStatement.executeQuery();

            while (resultSet.next()){
              admin = new Admin(resultSet.getInt("id"),resultSet.getString("username"),resultSet.getString("password")); //看上面，必须初始化值为null
            }

        } catch (SQLException e) {
            System.out.println(e);
        }finally {
            JDBCTool.close(connection,preparedStatement,resultSet);
        }
        return admin;
    }
}
